package controllers;

import helper.AliyunOssUploader;
import models.constants.DeletedStatus;
import models.merchant.Merchant;
import models.merchant.enums.VerifyState;
import models.msgtemp.merchant.WxMpMerchantMsgTemp;
import models.weixin.WebUser;
import models.weixin.WeixinData;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import play.Logger;
import play.mvc.Before;
import play.mvc.Controller;
import sun.misc.BASE64Decoder;
import util.common.ConvertUtil;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by youliangcheng on 17/7/1.
 */
public class LoginInCtrl extends Controller {

    public static final String MERCHANT_LOGIN_KEY = "merchant_login_key";


    /**
     * 继承LoginCtrl之后, 进入功能之前执行的操作
     * unless 过滤执行的方法,即 跳过Before操作的action
     *
     * @throws Throwable
     */
//    @Before(unless = {"regist", "registSave", "login", "loginIn", "getMerchant", "uploadImg","forgotPassword","verificationCodeLogin","verificationLogin"})
    @Before(only = {"loginOut"})
    public static void filter() throws Throwable {
        Merchant merchant = getMerchant();
        renderArgs.put("merchant", merchant);
    }


    public static void regist() {
        render();
    }

    public static void registSave(String mercahntName,
                                  String person,
                                  String phone,
                                  String loginName,
                                  String password,
                                  String imgSrc,
                                  String realName,
                                  String weChat,
                                  String teacher,
                                  String team,
                                  String classes,
                                  String address
        ) {
        Map<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isBlank(classes)) {
            resultMap.put("success", false);
            resultMap.put("msg", "班级不能为空");
            renderJSON(resultMap);
        }
        if (StringUtils.isBlank(realName)) {
            resultMap.put("success", false);
            resultMap.put("msg", "真实姓名不能为空");
            renderJSON(resultMap);
        }
        if (StringUtils.isBlank(mercahntName)) {
            resultMap.put("success", false);
            resultMap.put("msg", "商户名称不能为空");
            renderJSON(resultMap);
        }
        if (StringUtils.isBlank(person)) {
            resultMap.put("success", false);
            resultMap.put("msg", "联系人不能为空");
            renderJSON(resultMap);
        }
        if (StringUtils.isBlank(phone)) {
            resultMap.put("success", false);
            resultMap.put("msg", "联系电话不能为空");
            renderJSON(resultMap);
        }
        if (StringUtils.isBlank(address)) {
            resultMap.put("success", false);
            resultMap.put("msg", "商户地址不能为空");
            renderJSON(resultMap);
        }

        WebUser webUser = WebUser.findByPhone(phone);

        if (webUser == null) {
            resultMap.put("success", false);
            resultMap.put("msg", "注册商户前请在购物中心-个人设置中绑定手机号!");
            renderJSON(resultMap);
        }

        if (StringUtils.isBlank(loginName)) {
            resultMap.put("success", false);
            resultMap.put("msg", "登录名不能为空");
            renderJSON(resultMap);
        }
        if (StringUtils.isBlank(password)) {
            resultMap.put("success", false);
            resultMap.put("msg", "登录密码不能为空");
            renderJSON(resultMap);
        }
        Merchant merchant = Merchant.findByLoginName(loginName);
        if (merchant != null) {
            resultMap.put("success", false);
            resultMap.put("msg", "登录名已经存在,不可重复!");
            renderJSON(resultMap);
        }

        merchant = Merchant.findByName(mercahntName);
        if (merchant != null) {
            resultMap.put("success", false);
            resultMap.put("msg", "商户名已经被登记,请更换商户名称!");
            renderJSON(resultMap);
        }


        merchant = new Merchant();
        merchant.webUserId = webUser.id;
        merchant.name = mercahntName;
        merchant.servicePhone = phone;
        merchant.deleted = DeletedStatus.UN_DELETED;
        merchant.createAt = new Date();
        merchant.weixinData = WeixinData.findByWeixinDataId(2);//微信公众号目前固定为ID为2的公众号
        merchant.loginName = loginName;
        merchant.password = ConvertUtil.toMD5(password);
        merchant.verifyState = VerifyState.WAIT;
        merchant.imagePath = imgSrc;
        merchant.realName = realName;
        merchant.classes = classes;
        merchant.address = address;
        if (!StringUtils.isBlank(weChat)) {
            merchant.weChat = weChat;
        }
        if (!StringUtils.isBlank(teacher)) {
            merchant.teacher = teacher;
        }
        if (!StringUtils.isBlank(team)) {
            merchant.team = team;
        }
        merchant.save();
        merchant.linkId = ConvertUtil.toString(merchant.id);
        merchant.save();

        resultMap.put("success", true);
        resultMap.put("linkId", merchant.linkId);
        renderJSON(resultMap);

    }

    //登录页面
    public static void login() {
        render();
    }

    public static void loginIn(String loginName, String password) {
        Map<String, Object> resultMap = new HashMap<>();
        Merchant merchant = Merchant.findByLoginName(loginName);

        if (merchant == null) {
            resultMap.put("success", false);
            resultMap.put("msg", "商户不存在,请检查输入信息");
            renderJSON(resultMap);
        }

        if (!merchant.password.equals(ConvertUtil.toMD5(password))) {
            resultMap.put("success", false);
            resultMap.put("msg", "用户名或密码错误 , 请重试!");

            renderJSON(resultMap);
        }
        if (merchant.verifyState == VerifyState.NOTPASS) {
            resultMap.put("success", false);
            resultMap.put("msg", "商户审核未通过");
            renderJSON(resultMap);
        }else if (merchant.verifyState == VerifyState.CLOSE) {
            resultMap.put("success", false);
            resultMap.put("msg", "商户已被关闭");
            renderJSON(resultMap);
        }
       /* if(merchant.verifyState == VerifyState.WAIT || merchant.verifyState == null){
            resultMap.put("success" , false);
            resultMap.put("msg" , "请耐心等待管理员审核");
            renderJSON(resultMap);
        }*/
        Logger.info("merchant.name  : %s", merchant.name);
        session.put(MERCHANT_LOGIN_KEY, merchant.id);

        resultMap.put("success", true);
        renderJSON(resultMap);

    }

    public static Merchant getMerchant() {
        String merchantId = session.get(MERCHANT_LOGIN_KEY);
        if (StringUtils.isBlank(merchantId)) {
            // 跳转登录页面
            redirect("/login/index");
        }
        Merchant merchant = Merchant.findByMerchantId(Long.valueOf(merchantId));
        if (merchant == null) {
            // 商家不存在 跳转到登录页面
            redirect("/login/index");
        }
        return merchant;
    }

    /**
     * 退出登录
     */
    public static void loginOut() {
        String userId = session.get(MERCHANT_LOGIN_KEY);
        if (org.apache.commons.lang.StringUtils.isNotBlank(userId)) {
            session.remove(MERCHANT_LOGIN_KEY);
            redirect("/login/index");
        } else {
            redirect("/login/index");
        }
    }

    //加载图片
    public static void uploadImg(String imgData, String imgPath) {
        Logger.info("imgData=========== :%s", imgData);
        Logger.info("imgPath=========== :%s", imgPath);
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] result = decoder.decodeBuffer(imgData.split(",")[1]);
            InputStream sbs = new ByteArrayInputStream(result);

            String realPath = AliyunOssUploader.uploadPublicFile(sbs, imgPath, result.length);
            Logger.info("realPath=========== :%s", realPath);
            renderJSON("{\"realPath\":\"" + realPath + "\"}");
        } catch (IOException e) {
            Logger.info("Log home/uploadImg error :" + e.getMessage());
            e.printStackTrace();
        }

        renderJSON("{\"realPath\":\"\"}");
    }

    /**
     * 忘记密码
     */
    public static void forgotPassword() {
        render();
    }

    /**
     * 验证用户信息,并发送修改密码验证
     */
    public static void modfiyPassWord(String loginName, String idCode, String phone) {
        Map<String, Object> resultMap = new HashMap<>();
        Merchant merchant = Merchant.findByLoginNameAndPhone(loginName, idCode, phone);
        if (merchant == null) {
            resultMap.put("success", false);
            resultMap.put("msg", "商户信息 不存在,请重新输入!");
            renderJSON(resultMap);
        }

        if (merchant.webUserId == null) {
            resultMap.put("success", false);
            resultMap.put("msg", "商户微信信息不存在,无法发送验证码!");
            renderJSON(resultMap);
        }

        merchant.verificationCode = RandomStringUtils.randomNumeric(6);
        merchant.verificationCodeAt = new Date();
        merchant.save();
        WxMpMerchantMsgTemp.sendVerificationCodeToTheUser(merchant);

        resultMap.put("success", true);
        resultMap.put("msg", "已将确认信息发送至商户注册微信 , 请注意查收并确认!");
        renderJSON(resultMap);

    }



    //验证码登录页面
    public static void verificationCodeLogin() {
        render();
    }

    //验证登录
    public static void verificationLogin(String loginName, String verificationCode , String phone) {
        Map<String, Object> resultMap = new HashMap<>();
        Merchant merchant = Merchant.findByLoginName(loginName);

        if (merchant == null) {
            resultMap.put("success", false);
            resultMap.put("msg", "商户不存在,请检查输入信息");
            renderJSON(resultMap);
        }

        if (StringUtils.isBlank(merchant.verificationCode)) {
            resultMap.put("success", false);
            resultMap.put("msg", "验证码不存在,可能已经过期 , 请重新获取验证码!");

            renderJSON(resultMap);
        }


//        if(StringUtils.isBlank(phone)){
//            resultMap.put("success", false);
//            resultMap.put("msg", "请填写注册时的微信用户手机号码 !");
//
//            renderJSON(resultMap);
//        }
//

        if (merchant.verifyState == VerifyState.NOTPASS) {
            resultMap.put("success", false);
            resultMap.put("msg", "商户审核未通过");
            renderJSON(resultMap);
        }

        if (!merchant.verificationCode.equals(verificationCode)) {
            resultMap.put("success", false);
            resultMap.put("msg", "验证码错误 , 请重试!");

            renderJSON(resultMap);
        }
        session.put(MERCHANT_LOGIN_KEY, merchant.id);

        resultMap.put("success", true);
        renderJSON(resultMap);
    }


}
